package edu.hebeu.fragment.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.hebeu.R;
import edu.hebeu.fragment.BaseFragment;
import edu.hebeu.activity.GoodDetailActivity;
import edu.hebeu.activity.LoginActivity;
import edu.hebeu.adapters.ListGoodsAdapter;
import edu.hebeu.entity.ListGoodsResponse;
import edu.hebeu.network.API;
import edu.hebeu.network.APIConfig;
import edu.hebeu.network.MyCallback;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseFragment {

    private int i; // 决定当前要显示的第几页数据
    private int total; // 保存共几页数据
    private String searchKeyWord; // 表示搜索的关键字

    private List<ListGoodsResponse.Good> data; // 数据

    private SwipeRefreshLayout srl;
    private RecyclerView recycler_view;
    private EditText et_search;
    private Button btn_search;
    private ListGoodsAdapter adapter; // 声明适配器对象

    public HomeFragment() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews() {
        srl = (SwipeRefreshLayout) findViewByIdF(R.id.srl);
        recycler_view = (RecyclerView) findViewByIdF(R.id.recycler_view); // 获取RecyclerView组件
        et_search = (EditText) findViewByIdF(R.id.et_search);
        btn_search = (Button) findViewByIdF(R.id.btn_search);
        i = 1;
        searchKeyWord = null;
        data = new ArrayList<>();
        getFirstData();
    }

    /**
     * 将数据显示到页面的方法
     * @param goods
     */
    private void show(List<ListGoodsResponse.Good> goods) {
        // 创建布局管理器对象
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        // 设置垂直
//        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
        // 设置正向显示
        layoutManager.setReverseLayout(false);
        recycler_view.setLayoutManager(layoutManager); // 设置布局管理器

        // 创建适配器对象实例
        adapter = new ListGoodsAdapter(goods);
        recycler_view.setAdapter(adapter);

        // 初始化监听器
        initListener();
    }

    /**
     * 该方法用来初始化监听器
     */
    private void initListener() {

        // 给适配器对象添加Item被点击的监听器
        adapter.setOnItemClickListener(new ListGoodsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ListGoodsResponse.Good good) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", good.getId());
                bundle.putString("name", good.getName());
                bundle.putString("describe", good.getDescribe());
                bundle.putInt("price", good.getPrice());
                bundle.putInt("store", good.getStore());
                bundle.putString("src", good.getSrc());
                bundle.putInt("goods_category_id", good.getGoods_category_id());
                bundle.putInt("index", good.getIndex());
                bundle.putString("goods_category_name", good.getGoods_category_name());
                bundle.putString("user_username", good.getUser_username());
                bundle.putInt("root_category_id", good.getRoot_category_id());
                bundle.putString("root_category_name", good.getRoot_category_name());
                bundle.putString("address", good.getAddress());
                Intent intent = new Intent(context, GoodDetailActivity.class);
                intent.putExtra("good_data", bundle);

//                showToast("点击了" + good.toString(), 0, false);
                startActivity(intent);
            }
        });

        // 给适配器对象添加上拉加载更多的监听器
        adapter.setOnUpPullListener(new ListGoodsAdapter.OnUpPullListener() {
            @Override
            public void onUpPull(final ListGoodsAdapter.LoadMoreHolder loadMoreHolder) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        i++; // 将要显示的页数自增1
                        if (i <= total) { // 如果当前要显示的页在总页面之内,则进行如下(继续加载请求数据)
                            Map<String, Object> params = new HashMap<>();
                            params.put("i", i);
                            params.put("name_describe_goodsCategoryName_rootCategoryName", searchKeyWord);
                            requestGoods(params, loadMoreHolder);
                        } else { // 否则,即数据已经全部加载了
                            showToast("没有更多的商品啦！", 1, false);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loadMoreHolder.loadPrepare(ListGoodsAdapter.LoadMoreHolder.LOADER_STATE_NORMAL); // 将状态设置为正常
                                }
                            });
                        }
                    }
                }, 1000);
            }
        });

        setDownPullUploadListener(); // 下滑事件的监听器

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchKeyWord = et_search.getText().toString(); // 将搜索的关键字修改
                getFirstData();
            }
        });
    }

    /**
     * 这个方法用来实现下拉刷新(给绑定下拉事件的监听和处理)
     */
    private void setDownPullUploadListener() {
        // 设置该加载圈的颜色
        srl.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary,
                R.color.colorPrimaryDark, R.color.colorDark, R.color.colorMoneyRed);
        srl.setEnabled(true); // 让该组件(刷新)可用
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                searchKeyWord = null; // 将搜索的关键字修改为空
                et_search.setText(null); // 将搜索文本框的值修改为空
                // 执行刷新数据的操作
                getFirstData();
                // 更新UI
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 这里需要做两件事：1、让刷新停止；2、更新列表；
                        adapter.notifyDataSetChanged();
                        srl.setRefreshing(false);
                        showToast("刷新成功", 0, false);
                    }
                }, 2000); // 模拟延时2000毫秒
            }
        });
    }

    /**
     * 首次加载数据的方法
     */
    private void getFirstData() {
        Map<String, Object> params = new HashMap<>();
        params.put("i", 1); // 只传入参数 i=1，表示请求第一页的数据
        params.put("name_describe_goodsCategoryName_rootCategoryName", searchKeyWord);
        requestFirstGoods(params);
    }

    /**
     * 第一次加载商品信息的网络请求方法
     * @param params
     */
    private void requestFirstGoods(Map<String, Object> params) {
        API.requestConfig(APIConfig.URL.LIST_GOODS_URL, params, "")
            .postRequest(new MyCallback() {
                @Override
                public void onSuccess(String res) {
                    final ListGoodsResponse listGoodsResponse = (ListGoodsResponse) deSerialize(res, ListGoodsResponse.class);
                    if (listGoodsResponse.getCode() == 200) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                data.clear();
                                total = listGoodsResponse.getPage().getTotal();
                                data.addAll(listGoodsResponse.getPage().getGoods());
                                show(data);
                            }
                        });
                        Log.i("goodSuccessSerialize", listGoodsResponse.getPage().getGoods().toString());
                    } else if (listGoodsResponse.getCode() == 401) {
                        jumpActivity(LoginActivity.class, true);
                        showToast("身份过期", 1, true);
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    showToast("请求数据失败！", 0, true);
                }
            }, false);
    }

    /**
     * 请求加载更多商品信息的请求(除去第一次请求商品的其他请求)方法
     * @param params
     * @param loadMoreHolder
     */
    private void requestGoods(Map<String, Object> params, final ListGoodsAdapter.LoadMoreHolder loadMoreHolder) {
        API.requestConfig(APIConfig.URL.LIST_GOODS_URL, params, "")
            .postRequest(new MyCallback() {
                @Override
                public void onSuccess(String res) {
                    final ListGoodsResponse listGoodsResponse = (ListGoodsResponse) deSerialize(res, ListGoodsResponse.class);
                    if (listGoodsResponse.getCode() == 200) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                data.addAll(listGoodsResponse.getPage().getGoods());

                                adapter.notifyDataSetChanged();
                                loadMoreHolder.loadPrepare(ListGoodsAdapter.LoadMoreHolder.LOADER_STATE_LOADDING); // 将状态设置为正在加载
                            }
                        });
//                        Log.i("goodSuccessSerialize", listGoodsResponse.getPage().getGoods().toString());
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    showToast("请求数据失败！", 0, true);
                }
            }, false);
    }

}
